/*
 * Copyright (C) 2013 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License
 */

package com.lituoxy.dialer;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Trace;
import android.preference.PreferenceManager;
import android.support.annotation.Nullable;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;

import com.lituoxy.contacts.common.extensions.ExtensionsFactory;
import com.lituoxy.contacts.common.testing.NeededForTesting;
import com.lituoxy.dialer.database.FilteredNumberAsyncQueryHandler;
import com.lituoxy.dialer.database.HuaWeiIP;
import com.lituoxy.dialer.filterednumber.BlockedNumbersAutoMigrator;
import com.lituoxy.dialer.service.CassaService;
import com.lituoxy.dialer.util.UIUtil;
import com.huawei.rcs.RCSApplication;
import com.huawei.rcs.caasomp.CaasOmp;
import com.huawei.rcs.caasomp.CaasOmpCfg;
import com.huawei.rcs.call.CallApi;
import com.huawei.rcs.call.CallSession;
import com.huawei.rcs.call.ConferenceApi;
import com.huawei.rcs.hme.HmeAudio;
import com.huawei.rcs.stg.NatStgHelper;
import com.huawei.rcs.system.SysApi;
import com.huawei.rcs.tls.DefaultTlsHelper;
import com.huawei.rcs.upgrade.UpgradeApi;
import com.umeng.analytics.MobclickAgent;

public class DialerApplication extends RCSApplication {

    private static final String TAG = "DialerApplication";

    private static Context sContext;
    private String access_token =null;
    private HuaWeiIP huaWeiIPs;
    private boolean isLogin = false;
    private MediaPlayer mp = null;
    public CallSession applicationSession = null;
    public boolean Calling = false;

    public MediaPlayer getMp() {
        return mp;
    }

    public void setLogin(boolean login) {
        isLogin = login;
    }

    public HuaWeiIP getHuaWeiIPs() {
        return huaWeiIPs;
    }

    public void setHuaWeiIPs(HuaWeiIP huaWeiIPs) {
        this.huaWeiIPs = huaWeiIPs;
    }

    public String getToKey() {
        return access_token;
    }

    public void setToKey(String access_token) {
        this.access_token = access_token;
    }

    @Override
    public void onCreate() {
        Log.e("123", "程序开始 -2");
        super.onCreate();
        sContext = this;
        Log.e("123", "程序开始 -1");
        Trace.beginSection(TAG + " onCreate");
        Log.e("123", "程序开始 0");
        Trace.beginSection(TAG + " ExtensionsFactory initialization");
        Log.e("123", "程序开始1");
        ExtensionsFactory.init(getApplicationContext());
        Trace.endSection();
        Log.e("123", "程序开始2");
        new BlockedNumbersAutoMigrator(PreferenceManager.getDefaultSharedPreferences(this),
                new FilteredNumberAsyncQueryHandler(getContentResolver())).autoMigrate();
        Trace.endSection();
        Log.e("123", "程序开始3");
        MobclickAgent.setDebugMode(true);
        //初始化 huawei
        Log.e("123", "初始化 huawei");
        initHuaWei();
        Log.e("123", "初始化 huawei 完成");
        SysApi.setLogEncrypt(false);
        Log.e("123", "开启log");
    }

    /**
     * 初始化华为业务
     */
    private void initHuaWei() {
        UpgradeApi.init(getApplicationContext());
        HmeAudio.setup(getApplicationContext());
        //HmeVideo.setup(this);
        CallApi.init(getApplicationContext());
        CallApi.setConfig(CallApi.CONFIG_MAJOR_TYPE_VIDEO_PREFER_SIZE,
                CallApi.CONFIG_MINOR_TYPE_DEFAULT, "2");
        SysApi.loadTls(new DefaultTlsHelper());
        SysApi.loadStg(new NatStgHelper());
        //SysApi.loadStg(new SvnStgHelper());

        ConferenceApi.initiateApi(getApplicationContext());

        CaasOmp.init();
        CaasOmpCfg.setString(CaasOmpCfg.EN_OMP_CFG_SERVER_IP, "205.177.226.80");
        CaasOmpCfg.setUint(CaasOmpCfg.EN_OMP_CFG_SERVER_PORT, 8543);

	   /* UI must set  the interface for safety certification.
       see detail in Developer's Guide*/
        // SysApi.setTrustCaFilePath("/rootcert.pem");

        //Start the service and to have it run in the BAM.
        Intent mIntent = new Intent();
        mIntent.setAction(CassaService.SERVICE_NAME);//你定义的service的action
        mIntent.setPackage(getPackageName());//这里你需要设置你应用的包名
        getApplicationContext().startService(mIntent);
        //启动  接听电话广播
        LocalBroadcastManager.getInstance(getApplicationContext())
                .registerReceiver(callInvitationReceiver, new IntentFilter(CallApi.EVENT_CALL_INVITATION));
        //系统持久存在 广播
    }


    public boolean isCalling = false;
    BroadcastReceiver callInvitationReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            CallSession session = (CallSession) intent.getSerializableExtra(CallApi.PARAM_CALL_SESSION);
            UIUtil.cancelProgressDialog();

            if (session.getType() == CallSession.TYPE_VIDEO_SHARE) {
                return;
            }
            isCalling = true;
            applicationSession = session;
            startMP3();
            //打开接听界面
            Intent newIntent = new Intent(context, ACT_DemoCallIncoming.class);
            newIntent.putExtra("session_id", session.getSessionId());
            newIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(newIntent);
        }
    };

    private void startMP3() {
        mp = createLocalMp3();
        mp.setLooping(true);
        mp.start();//开始播放

        /*//监听音频播放完的代码，实现音频的自动循环播放
        mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {

            @Override
            public void onCompletion(MediaPlayer arg0) {
                if (mp != null) {
                    mp.start();
                    mp.setLooping(true);
                }
            }
        });*/
    }

    /**
     * 创建本地MP3
     *
     * @return
     */
    public MediaPlayer createLocalMp3() {
        /**
         * 创建音频文件的方法：
         * 1、播放资源目录的文件：MediaPlayer.create(MainActivity.this,R.raw.beatit);//播放res/raw 资源目录下的MP3文件
         * 2:播放sdcard卡的文件：mediaPlayer=new MediaPlayer();
         *   mediaPlayer.setDataSource("/sdcard/beatit.mp3");//前提是sdcard卡要先导入音频文件
         */
        MediaPlayer mp = MediaPlayer.create(this, R.raw.play);
        AudioManager audioMgr = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        // 获取最大音乐音量
        int maxVolume = audioMgr.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        audioMgr.setStreamVolume(AudioManager.STREAM_MUSIC, maxVolume,
                AudioManager.FLAG_PLAY_SOUND);
        return mp;
    }

    @Override
    public void onTerminate() {
        super.onTerminate();
        //关闭 广播
        LocalBroadcastManager.getInstance(getApplicationContext()).unregisterReceiver(callInvitationReceiver);
    }

    @Nullable
    public static Context getContext() {
        return sContext;
    }

    @NeededForTesting
    public static void setContextForTest(Context context) {
        sContext = context;
    }

    public boolean getIsLogin() {
        return this.isLogin;
    }

    public void stopMp() {
        mp = null;
    }
}
